require('./check-versions')();

// 支持配置NODE_ENV
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
const ora = require('ora');
const chalk = require('chalk');
const webpack = require('webpack');
const webpackConfig = require('./webpack.production.conf');

module.exports = () => new Promise((resolve, reject) => {
  console.time(chalk.green('总耗时'));
  const spinner = ora('构建项目开始…');
  spinner.start();

  process.on('unhandledRejection', err => {
    console.log('unhandledRejection==>', err.stack);
    spinner.stop();
    reject();
  });
  process.on('uncaughtException', err => {
    console.log('uncaughtException==>', err.stack);
    spinner.stop();
    reject();
  });

  webpack(webpackConfig, (err, stats) => {
    spinner.stop();
    if (err) {
      throw err;
    }

    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n\n');

    if (stats.hasErrors()) {
      console.log(chalk.red('打包错误。\n'));
      process.exit(1);
    }

    console.timeEnd(chalk.green('总耗时'));
    console.log(chalk.cyan('打包完成。\n'));
    resolve();
  });
})
